package com.xzzz.common.wechat.enums;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;

import java.io.File;

/**
 * 微信错误码转为枚举的工具类
 *
 * <p>在 <a href='https://developers.weixin.qq.com/doc/oplatform/Return_codes/Return_code_descriptions_new.html'>微信官方文档</a>, 使用F12控制台
 * 复制错误码的tbody标签, 保存在resource目录下的wxerrorcode.txt文件中, 然后执行此代码即可
 *
 * @author xzzz
 */
@SuppressWarnings("all")
public class WxErrorCodeEnumGenUtil {

    /**
     * 保存在resource目录下的文件名
     */
    private static final String FILE_NAME = "wxerrorcode.txt";

    private static final String TR_TAG_STA = "<tr>";
    private static final String TR_TAG_END = "</tr>";
    private static final String TD_TAG_STA = "<td>";
    private static final String TD_TAG_END = "</td>";

    public static void main(String[] args) {

        String all = readFile().toString();
        while (StrUtil.contains(all, TR_TAG_STA)) {

            int trSta = StrUtil.indexOfIgnoreCase(all, TR_TAG_STA);
            int trEnd = StrUtil.indexOfIgnoreCase(all, TR_TAG_END) + 5;

            String trTarget = StrUtil.sub(all, trSta, trEnd);

            String[] tdValues = new String[3];

            for (int j = 0; j < 3; j++) {
                int tdSta = StrUtil.indexOfIgnoreCase(trTarget, TD_TAG_STA) + 4;
                int tdEnd = StrUtil.indexOfIgnoreCase(trTarget, TD_TAG_END);
                tdValues[j] = format(StrUtil.sub(trTarget, tdSta, tdEnd));
                trTarget = StrUtil.sub(trTarget, tdEnd + 5, trTarget.length());
            }
            printEnumItem(tdValues);

            all = StrUtil.sub(all, trEnd, all.length());
        }

    }

    /**
     * 读取文件,返回文件内容
     */
    private static String readFile () {
        File file = FileUtil.file(FILE_NAME);
        String fileContent = FileUtil.readString(file, "UTF-8");
        if (StrUtil.isBlank(fileContent)) {
            throw new IllegalArgumentException("未获取到文件内容, 请检查文件");
        }
        return fileContent;
    }

    /**
     * 文本字符转义
     */
    private static String format(String str) {
        str = StrUtil.replace(str, "\"", "");
        str = StrUtil.replace(str, "\\uxxxx", "反斜杠uxxxx");
        return str;
    }

    /**
     * 输出为枚举值
     */
    private static void printEnumItem(String... str) {
        System.out.println(String.format("WXCODE_%s (\"%s\",\"%s\",\"%s\", \"\"),", str[0], str[0], str[1], str[2]));
    }

}
